import * as echarts from '../../ec-canvas/echarts';
import router from "../../utils/router";
import store from '../../utils/store'
import {FaultType, FaultLevel} from "../../enum/laneStatus";
import {
    getDay
} from '../../utils/date'
import dayjs from "dayjs";


const app = getApp()
const Api = app.Api
Page({
    data: {
        role: 1,
        FaultType,
        FaultLevel,
        allFaultCount: '暂无数据', // 所有车辆
        ec: {
            lazyLoad: true
        },
        datalist: [],
        pageIndex: 0,
        pageSize: 3,
        xAxisArr: [], // x轴的数组
        yAxisArr: [], // y轴的数组
        startTime: '',
        endTime: '',
        noEchartsData: false,
        todayFaultCount: '暂无数据',
        show: false,
        minDate: new Date(2020, 0, 1).getTime(),
        maxDate: new Date().getTime(),
    },

    /**
     * 页面加载
     * @returns {Promise<void>}
     */
    async onLoad() {
        this.echartsRef = this.selectComponent("#mychart")
        const startTime = getDay(-7)
        const endTime = getDay(0)
        this.setData({
            startTime,
            endTime
        })
    },

    /**
     * 点击图表上方的时间区间
     */
    handleClickTime() {
        this.setData({
            show: true
        })
    },

    /**
     * 关闭日期选择控件
     */
    onClose() {
        this.setData({
            show: false
        })
    },
    /**
     * 日期选择控件确认事件
     * @param event
     * @returns {Promise<void>}
     */
    async onConfirm(event) {
        let [start, end] = event.detail;
        start = dayjs(start).format('YYYY-MM-DD')
        end = dayjs(end).format('YYYY-MM-DD')
        const factoryId = store.getItem("factoryId")
        this.setData({
            startTime: start,
            endTime: end,
            show: false
        })
        try {
            const res = await app.clientGet(`${app.ClientApi.getFaultCount}/${start}/${end}/factoryId/${factoryId}`)
            const xAxisArr = res.map(item => item.createdAt.slice(5))
            const yAxisArr = res.map(item => {
                if (item.count === undefined) {
                    item.count = 0
                }
                return item.count
            })
            this.setData({
                noEchartsData: false,
                xAxisArr,
                yAxisArr
            })
            this.initCharts()
        } catch (e) {
            this.setData({
                noEchartsData: true,
                xAxisArr: [],
                yAxisArr: []
            })
            console.log('e', e)
        }
    },

    /**
     * 获取累计故障次数
     * @returns {Promise<void>}
     */
    async getAllCount() {
        const startTime = '2019-01-01'
        const endTime = dayjs().format('YYYY-MM-DD')
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientGet(`${app.ClientApi.getFaultCount}/${startTime}/${endTime}/factoryId/${factoryId}`)
            const sums = res.map(item => {
                if (item.count) {
                    if (item.count === undefined) {
                        item.count = 0
                    }
                    return item.count
                }
            })
            const totalCount = sums.reduce((total, item) => {
                if (item === undefined) {
                    item = 0
                }

                return total + item
            }, 0)
            this.setData({
                allFaultCount: totalCount
            })
        } catch (e) {
            console.log(e)
        }

    },
    /**
     * 获取故障详情列表
     * @returns {Promise<void>}
     */
    async getOrderList() {
        this.data.pageIndex++
        const factoryId = store.getItem("factoryId")
        const startTime = '2019-01-01'
        const endTime = dayjs().format('YYYY-MM-DD')
        try {
            app.clientPost(`${app.ClientApi.getFaultInfo}/page-num/${this.data.pageIndex}/page-size/${this.data.pageSize}/factoryId/${factoryId}`, {
                startTime: startTime + ' 00:00:00',
                endTime: endTime + ' 23:59:59',
            }).then((res) => {
                this.setData({
                    datalist: res.list
                })
            })
        } catch (e) {
            console.log('e', e)
        }
    },

    /**
     * 获取今日故障次数
     * @returns {Promise<void>}
     */
    async getLoadingData() {
        const factoryId = store.getItem("factoryId")
        const startTime = dayjs().format('YYYY-MM-DD')
        const endTime = dayjs().format('YYYY-MM-DD')
        try {
            const res = await app.clientGet(`${app.ClientApi.getFaultCount}/${startTime}/${endTime}/factoryId/${factoryId}`, {}, {
                loading:false
            })
            this.setData({
                todayFaultCount: res[0].count
            })
        }catch (e) {
            this.setData({
                todayCars: '暂无数据'
            })
        }
    },

    /**
     * 获取图表数据
     * @returns {Promise<void>}
     */
    async handleSearch() {
        const factoryId = store.getItem("factoryId")
        const start = getDay(-7)
        const end = getDay(0)
        try {
            const res = await app.clientGet(`${app.ClientApi.getFaultCount}/${start}/${end}/factoryId/${factoryId}`)
            const xAxisArr = res.map(item => item.createdAt.slice(5))
            const yAxisArr = res.map(item => {
                if (item.count === undefined) {
                    item.count = 0
                }
                return item.count
            })
            this.setData({
                noEchartsData: false,
                xAxisArr,
                yAxisArr
            })
            this.initCharts()
        } catch (e) {
            this.setData({
                noEchartsData: true,
                xAxisArr: [],
                yAxisArr: []
            })
            console.log('e', e)
        }
    },

    // 初始化图表方法
    initCharts() {
        this.echartsRef.init((canvas, width, height) => {
            const Chart = echarts.init(canvas, null, {
                width: width,
                height: height,
            });
            Chart.clear()
            Chart.setOption(this.getOption())
            return Chart
        })
    },

    // 图表配置项
    getOption() {
        let option = {
            title: {
                text: '',
            },
            grid: {
                left: '15%',
                bottom: '10%',
                top: "15%",
                right: "40"
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: this.data.xAxisArr,
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                type: 'line',
                smooth: true,
                color: '#0065ff',
                data: this.data.yAxisArr,
                label: {
                    show: true,
                    position: 'top',
                    color: 'red'
                }
            }]
        };
        return option
    },

    /**
     * 页面onShow生命周期
     * @returns {Promise<void>}
     */
    async onShow() {
        this.setData({
            xAxisArr: [],
            yAxisArr: []
        })
        const startTime = store.getItem('startTime') || getDay(-7)
        const endTime = store.getItem('endTime') || getDay(0)
        const phoneNumber = store.getItem("phoneNumber")
        this.setData({
            startTime,
            endTime
        })
        await this.getUserInfo(phoneNumber)
        await this.getAllCount()
        await this.getOrderList()
        await this.getLoadingData()
        await this.handleSearch()
    },

 // 获取用户权限
 async getUserInfo(phoneNumber) {
    const res = await app.get(`${Api.getUserInfo}?phoneNumber=${phoneNumber}`)
    const role =  res[0].jurisdiction
    this.setData({
        role
    })
},

    /**
     * 跳转到故障详情列表页
     */
    toMoreFault() {
        router.push('fault-list')
    },

    /**
     * 页面卸载生命周期
     */
    onUnload() {
        this.setData({
            noEchartsData: false,
        })
    }

});
